package info.sean.util;


import info.sean.logger.GmfLogger;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import info.sean.util.DateUtil.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ServiceUtil {
	private static Logger logger = GmfLogger.getLogger(ServiceUtil.class);
	public static final long ONE_MIN_MILLISECONDS = (long) 1000 * 60;
	private static  final  String DATE_PATTERN = "yyyy-MM-dd";
//	public static Map<String, Object> getCommonCompanyMap() {
//		Map<String, Object> map = new HashMap<>();
//		map.put("companyName", ConfigService.getAppConfig().getProperty("usercenter.requestparams.companyname", ""));
//		return map;
//	}
	
	public static Map<String, Object> getMap() {
		Map<String, Object> map = new HashMap<>();
		return map;
	}

	/**
	 * @param md5from
	 * @param seeds
	 * @return
	 */
	public static boolean validateMD5Mac(String md5from, String[] seeds) {
		boolean theSame = false;
		try {
			if (StringUtils.isBlank(md5from)) {
				return false;
			}
			if (seeds == null || seeds.length == 0) {
				return false;
			}
			String md5to = DigestUtils.md5Hex(StringUtils.join(seeds, ""));
			return md5from.trim().equalsIgnoreCase(md5to);
		} catch (Exception e) {
			logger.error("validate input mac error", e);
			theSame = false;
		}
		return theSame;
	}

	/**
	 * validate mobile no format
	 *
	 * @param mobile
	 * @return
	 */
	public static boolean validateMobile(String mobile) {
		boolean flag = false;
		try {
			String regEx = "^\\d{11}$";
			if (StringUtils.isNotBlank(mobile)) {
				return mobile.matches(regEx);
			}
		} catch (Exception e) {
			logger.error("validate mobile error", e);
			flag = false;
		}
		return flag;
	}

	public static boolean validateChannel(String channel) {
		boolean flag = false;
		try {
			String regEx = "\\d{4}";
			if (StringUtils.isNotBlank(channel)) {
				return channel.matches(regEx);
			}
		} catch (Exception e) {
			logger.error("validate channel error", e);
			flag = false;
		}
		return flag;
	}

	public static boolean validateBankCardNo(String cardNo) {
		boolean flag = false;
		try {
			String regEx = "\\d{10,20}";
			if (StringUtils.isNotBlank(cardNo)) {
				return cardNo.matches(regEx);
			}
		} catch (Exception e) {
			logger.error("validate bank card no error", e);
			flag = false;
		}
		return flag;
	}

	public static boolean vaslidateEmail(String email) {
		boolean flag = false;
		try {
			String regEx = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
			if (StringUtils.isNotBlank(email)) {
				return email.matches(regEx);
			}
		} catch (Exception e) {
			logger.error("validate email error", e);
			flag = false;
		}
		return flag;
	}

	/**
	 * 身份证格式校验
	 *
	 * @param IDStr
	 * @return
	 */
	public static boolean validateIdNo(String IDStr) {
		IDStr = IDStr.toUpperCase();
		//        String errorInfo = "";// 记录错误信息
		String[] valCodeArr = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
		String[] wi = {"7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2"};
		String ai = "";
		// ================ 号码的长度 15位或18位 ================
		if (IDStr.length() != 15 && IDStr.length() != 18) {
			//            errorInfo = "身份证号码长度应该为15位或18位。";
			return false;
		}
		// =======================(end)========================
		// ================ 数字 除最后以为都为数字 ================
		if (IDStr.length() == 18) {
			ai = IDStr.substring(0, 17);
		} else if (IDStr.length() == 15) {
			ai = IDStr.substring(0, 6) + "19" + IDStr.substring(6, 15);
		}
		if (!isNumeric(ai)) {
			//            errorInfo = "身份证15位号码都应为数字 ; 18位号码除最后一位外，都应为数字。";
			return false;
		}
		// =======================(end)========================

		// ================ 出生年月是否有效 ================
		String strYear = ai.substring(6, 10);// 年份
		String strMonth = ai.substring(10, 12);// 月份
		String strDay = ai.substring(12, 14);// 月份
		if (!isDate(strYear + "-" + strMonth + "-" + strDay)) {
			//            errorInfo = "身份证生日无效。";
			return false;
		}
		GregorianCalendar gc = new GregorianCalendar();
		SimpleDateFormat s = new SimpleDateFormat(DATE_PATTERN);
		try {
			if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150
					|| (gc.getTime().getTime() - s.parse(strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {
				//                errorInfo = "身份证生日不在有效范围。";
				return false;
			}
		} catch (NumberFormatException e) {
			logger.error("validate id no error", e);
		} catch (ParseException e) {
			logger.error("validate id no error", e);
		}
		if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) {
			//            errorInfo = "身份证月份无效";
			return false;
		}
		if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
			//            errorInfo = "身份证日期无效";
			return false;
		}
		// =====================(end)=====================

		// ================ 地区码时候有效 ================
		HashMap<String, String> h = getAreaCode();
		if (h.get(ai.substring(0, 2)) == null) {
			//            errorInfo = "身份证地区编码错误。";
			return false;
		}
		// ==============================================

		// ================ 判断最后一位的值 ================
		int totalmulAiWi = 0;
		for (int i = 0; i < 17; i++) {
			totalmulAiWi = totalmulAiWi + Integer.parseInt(String.valueOf(ai.charAt(i))) * Integer.parseInt(wi[i]);
		}
		int modValue = totalmulAiWi % 11;
		String strVerifyCode = valCodeArr[modValue];
		ai = ai + strVerifyCode;

		if (IDStr.length() == 18) {
			if (ai.equals(IDStr) == false) {
				//                errorInfo = "身份证无效，不是合法的身份证号码";
				if (h.get(ai.substring(0,2)) != null){
					String natives = h.get(ai.substring(0, 2));
					System.out.println("地区 = " + natives+"————无效的假身份证号："+ai);
				}
				return false;
			}
		} else {
			return true;
		}
		if (h.get(ai.substring(0,2)) != null){
			String natives = h.get(ai.substring(0, 2));
			System.out.println("地区 = " + natives+"————有效身份证号："+ai);
		}
		// =====================(end)=====================
		return true;
	}

	/**
	 * 功能：设置地区编码
	 *
	 * @return HashMap 对象
	 */
	@SuppressWarnings("unchecked")
	private static HashMap getAreaCode() {
		HashMap<String, String> hashMap = new HashMap<>();
		hashMap.put("11", "北京");
		hashMap.put("12", "天津");
		hashMap.put("13", "河北");
		hashMap.put("14", "山西");
		hashMap.put("15", "内蒙古");
		hashMap.put("21", "辽宁");
		hashMap.put("22", "吉林");
		hashMap.put("23", "黑龙江");
		hashMap.put("31", "上海");
		hashMap.put("32", "江苏");
		hashMap.put("33", "浙江");
		hashMap.put("34", "安徽");
		hashMap.put("35", "福建");
		hashMap.put("36", "江西");
		hashMap.put("37", "山东");
		hashMap.put("41", "河南");
		hashMap.put("42", "湖北");
		hashMap.put("43", "湖南");
		hashMap.put("44", "广东");
		hashMap.put("45", "广西");
		hashMap.put("46", "海南");
		hashMap.put("50", "重庆");
		hashMap.put("51", "四川");
		hashMap.put("52", "贵州");
		hashMap.put("53", "云南");
		hashMap.put("54", "西藏");
		hashMap.put("61", "陕西");
		hashMap.put("62", "甘肃");
		hashMap.put("63", "青海");
		hashMap.put("64", "宁夏");
		hashMap.put("65", "新疆");
		hashMap.put("71", "台湾");
		hashMap.put("81", "香港");
		hashMap.put("82", "澳门");
		hashMap.put("91", "国外");
		return hashMap;
	}

	/**
	 * 功能：判断字符串是否为数字
	 *
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		return isNum.matches();
	}

	/**
	 * 功能：判断字符串是否为日期格式
	 *
	 * @param strDate
	 * @return
	 */
	public static boolean isDate(String strDate) {
		Pattern pattern = Pattern.compile(
				"^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
		Matcher m = pattern.matcher(strDate);
		return m.matches();
	}

	/**
	 * 判断时间是否符合格式
	 *
	 * @param date
	 * @return
	 */
	public static boolean validateData(String date, String format) {
		boolean result = true;
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			sdf.setLenient(false);
			sdf.parse(date);

		} catch (ParseException e) {
			result = false;
		}
		return result;
	}

	/**
	 * 校验密码格式
	 *
	 * @param str
	 * @return
	 */
	public static boolean validatePassword(String str) {
		Pattern pattern = Pattern.compile(
				"^(?![\\d]+$)(?![a-zA-Z]+$)(?![~!@#$%^&*()\\-_=+\\[\\];',./\\\\]+$)[\\da-zA-Z~!@#$%^&*()\\-_=+\\[\\];',./\\\\]{6,20}$");
		Matcher m = pattern.matcher(str);
		return m.matches();
	}

	/**
	 * 获取集团渠道用户权重比例
//	 * @param channels
	 * @return
	 */
//	public static String getUserCenterChannelByWeight(List<String> channels) {
//		String userCenterChannelWeight = ConfigService.getAppConfig().getProperty("usercenter.channel.weight", "");
//		String[] weights = userCenterChannelWeight.split(",");
//		for (String s : weights) {
//			if (channels.contains(s)) {
//				return s;
//			}
//		}
//		return null;
//	}

//	public static String getUserCenterChannelByWeight(Map<String, String> channelAndUserId) {
//		List<String> channels = new ArrayList<>();
//		Iterator<Map.Entry<String, String>> iterator = channelAndUserId.entrySet().iterator();
//		while (iterator.hasNext()) {
//			channels.add(iterator.next().getKey());
//		}
//		return getUserCenterChannelByWeight(channels);
//	}

	public static boolean avatarPicTypeValidate(String type, String allowTypes) {
		boolean allowed = false;
		if (StringUtils.isBlank(allowTypes)) {
			return allowed;
		}
		String[] types = allowTypes.split(",");
		for (int i = 0; i < types.length; i++) {
			if (type.equals(types[i])) {
				allowed = true;
				break;
			}
		}
		return allowed;
	}

	public static int getExpiredMin(Date date) {
		Date dateNow = new Date();
		long times = date.getTime() - dateNow.getTime();
		return ((int) ((times > 0 ? times : -times) / ONE_MIN_MILLISECONDS));
	}

	/**
	 * 手机号数据脱敏
	 * 16721316761 转换为 167****6761
	 *
	 * @param mobile
	 * @return
	 */
	public static String mobileDesensitization(String mobile) {
		return desensitization("(\\d{3})\\d{4}(\\d{4})", "$1****$2", mobile);
	}

	/**
	 * 身份证号脱敏
	 * 4304*****7733
	 *
	 * @param idNo
	 * @return
	 */
	public static String idNoDesensitization(String idNo) {
		return desensitization("(\\d{4})\\d{10}(\\w{4})", "$1*****$2", idNo);
	}

	/**
	 * 数据脱敏
	 *
	 * @param pattern 脱敏拆分，将数据拆为几部分
	 * @param save    选择保留的部分
	 * @param data    需要脱敏的数据
	 * @return 脱敏后的数据
	 */
	public static String desensitization(String pattern, String save, String data) {
		if (StringUtils.isBlank(data)) {
			return data;
		}
		return data.replaceAll(pattern, save);
	}

	/**
	 * validate mobile no format
	 *
	 * @param ip
	 * @return
	 */
	public static boolean validateIP(String ip) {
		boolean flag = false;
		try {
			String regEx = "((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))";
			if (StringUtils.isNotBlank(ip)) {
				return ip.matches(regEx);
			}
		} catch (Exception e) {
			logger.error("validate ip error", e);
			flag = false;
		}
		return flag;
	}

	public static void main(String[] args) {
		Pattern pattern = Pattern.compile(
				"^(?![\\d]+$)(?![a-zA-Z]+$)(?![~!@#$%^&*()\\-_=+\\[\\];',./\\\\]+$)[\\da-zA-Z~!@#$%^&*()\\-_=+\\[\\];',./\\\\]{6,20}$");
		Matcher m = pattern.matcher("qqqqqqqqqqqqqq");
		System.out.println(m.matches());
	}

}
